use model_graph_common::config::get_peer_config;
use serde::{Serialize, Serializer};
use std::{collections::HashMap, sync::Mutex};
use tauri::{command, AppHandle, Runtime, State, Window};

use data_transform::DefaultDataTransformer;
use serde_json::Value as JsonValue;
use std::path::PathBuf;
use union_connector::UnionConnector;

use super::ContextState;
use super::Error;
use super::Result;

use container_core::workflow::{SimpleWorkflowEngine, WorkflowDocumentJsonReader};
use model_graph_types::{
    container::workflow::{
        WorkflowDocumentReadeOptions, WorkflowDocumentReader, WorkflowEngine,
        WorkflowEngineCompileOptions, WorkflowEngineRunOptions, WorkflowResult,
    },
    database::{ConnectorProtocol, DataSource, DatabaseType},
    modeling::Value,
    modeling::{Class, ModelingReader, ModelingWriter},
};

#[command]
pub async fn workflow_execute<R: Runtime>(
    _app: AppHandle<R>,
    _window: Window<R>,
    state: State<'_, ContextState>,
    file: String,
    args: HashMap<String, serde_json::Value>,
    compile_options: WorkflowEngineCompileOptions,
    execute_options: WorkflowEngineRunOptions,
) -> Result<WorkflowResult> {
    //
    let document = WorkflowDocumentJsonReader::default()
        .read_from_json_file(&file, WorkflowDocumentReadeOptions::default())
        .await?;

    let mut arg_values = HashMap::new();
    for (key, value) in args {
        arg_values.insert(
            key.clone(),
            value.try_into().map_err(|err| anyhow::anyhow!("{}", err))?,
        );
    }
    //
    let res = SimpleWorkflowEngine::default()
        .fetch(document, arg_values, compile_options, execute_options)
        .await?;

    Ok(res)
}
